package yxy.game.pm2.command.worldboss;

import org.joda.time.DateTime;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.module.AreaModule;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.WorldBossMessage;
import yxy.game.pm2.module.worldboss.RankWorldBoss;
import yxy.game.pm2.module.worldboss.WorldBossHandle;
import yxy.game.pm2.module.worldboss.WorldBossModule;
import yxy.game.pm2.module.worldboss.WorldBossPlayer;

import java.util.Collection;

/** 世界BOSS 世界BOSS */
@MessageType(proto = Command.WorldBossUI, classtype = WorldBossMessage.WorldBossUIRequest.class)
public class CMD_WorldBossUI extends Command<WorldBossMessage.WorldBossUIRequest> {

	@Override
	public void execute(MessageSource messageSource, WorldBossMessage.WorldBossUIRequest request) {
		String playerCode = messageSource.getTag();

		WorldBossMessage.WorldBossUIResponse.Builder response = WorldBossMessage.WorldBossUIResponse.newBuilder();

		// 世界等级判断
		WorldBossHandle bossHandle = new WorldBossHandle();
		AreaBean areaBean = AreaModule.area(playerCode);
		Result result = bossHandle.checkWorldLevel(areaBean);
		if (!result.equals(Result.Success)) {
			if (result.equals(Result.WorldBossNotOpen)) {
				DateTime opentime = bossHandle.openTime(DateTime.now());
				response.setOpentime(opentime.getMillis());
			}
			send(messageSource, response, result);
			return;
		}

		WorldBossModule worldBossModule = WorldBossModule.get(playerCode);
		WorldBossPlayer worldBossPlayer = WorldBossPlayer.get(playerCode);
		RankWorldBoss rankWorldBoss = new RankWorldBoss(areaBean);

		response.setTimes(worldBossPlayer.remainTimes());
		response.setBuytimes(worldBossPlayer.remainBuyTimes());
		response.setDamage(worldBossPlayer.getDamage());
		response.setTotalDamage(worldBossModule.getTotalDamage());

		Collection<RankEntry> top = rankWorldBoss.top(3);
		int rank = 0;
		for (RankEntry entry : top) {
			String pCode = entry.getKey();
			long damage = entry.getValue();
			PlayerBean playerBean = PlayerBean.get(pCode);

			WorldBossMessage.TopWorldBoss.Builder builder = WorldBossMessage.TopWorldBoss.newBuilder();
			builder.setRank(++rank);
			builder.setDamage(damage);
			builder.setName(playerBean.getName());
			response.addTop(builder);
		}
		response.setRank(rankWorldBoss.rank(playerCode));

		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, WorldBossMessage.WorldBossUIResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}